package com.gfl.trivialrestclient.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import com.gfl.trivialrestclient.controllers.forms.AjaxSubmitionStatus;

/**
 * Ajax auth failure handler. Ajax detection is based on
 * X-Requested-With:XMLHttpRequest HTTP header.
 * 
 * @author Bedlam
 * 
 */
public class AjaxAuthentificationFailureHandler extends
		SimpleUrlAuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {

		//detect ajax request
		if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
			response.setContentType("application/json; charset=UTF-8");

			AjaxSubmitionStatus failureStatus = new AjaxSubmitionStatus(false);
			failureStatus.setErrorMessage(exception.getMessage());

			response.getWriter().print(
					new ObjectMapper().writeValueAsString(failureStatus));
			response.getWriter().flush();

		} else {
			// traditional html failure
			super.onAuthenticationFailure(request, response, exception);
		}

	}
}
